package cn.tedu._03vehicle.base.exception;

import cn.tedu._03vehicle.base.response.JsonResult;
import cn.tedu._03vehicle.base.response.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

import static jdk.nashorn.internal.runtime.regexp.joni.Config.log;
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    public JsonResult doHandleIllegalArgumentException(IllegalArgumentException ex){
        //获取异常提示消息:throw new IllegalArgumentException("车辆ID不能小于0");
        String data = ex.getMessage();
        log.error("IllegalArgumentException:{}", data);
        //{"state":3000,"message":"操作失败","data":"车辆ID不能小于0"}
        return new JsonResult(StatusCode.OPERATION_FAILED, data);
    }

    @ExceptionHandler
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException ex){
        String data = ex.getFieldError().getDefaultMessage();
        log.error("MethodArgumentNotValidException:{}",data);
        return new JsonResult(StatusCode.VALIDATED_ERROR,data);
    }

    @ExceptionHandler
    public JsonResult doHandler (ConstraintViolationException ex){
        String data = ex.getMessage().split(":")[1].trim();
        log.debug("ConstraintViolationException:{}",data);
        return new JsonResult(StatusCode.VALIDATED_ERROR,data);
    }

    @ExceptionHandler
    public JsonResult doHandleRuntimeException(RuntimeException ex){
        String data = ex.getMessage();
        log.error("RuntimeException:{}",data);
        return new JsonResult(StatusCode.OPERATION_FAILED,data);
    }

    @ExceptionHandler
    public JsonResult doHandleThrowable(Throwable ex){
        String data = ex.getMessage();
        log.error("Throwable:{}",data);
        return new JsonResult(StatusCode.THROWABLE_ERROR,data);
    }

}
